<template>
  <div class="port-message">
    <div class="drag-box" ref="dragImg" :style="dragStyle" style="position: fixed; width: 200px; height: 300px">
      <img style="width: 100%" :src="imgSrc" alt="" srcset="" :draggable="false" />
    </div>
  </div>
</template>

<script setup lang="ts">
// import { ref, reactive } from 'vue'
const route = useRoute()
import { useDraggable } from '@vueuse/core'

// 创建频道
const channel = new BroadcastChannel('card')
channel.onmessage = e => {
  const clientPosition = screenToClient(e.data[0], e.data[1])
  dragStyle.value = `left: ${clientPosition[0]}px; top: ${clientPosition[1]}px`
}

// 拖动
const dragImg = ref<HTMLElement | null>(null)
let { x, y } = useDraggable(dragImg, {
  initialValue: { x: 40, y: 40 },
  onMove: position => {
    sendMessage(position.x, position.y)
  }
})

const sendMessage = (x: number, y: number) => {
  const screenPosition = clientToScreen(x, y)
  dragStyle.value = `left: ${x}px; top: ${y}px`
  channel.postMessage(screenPosition)
}

const barHeight = () => {
  return window.innerHeight - window.outerHeight
}

// 视口坐标 -- 屏幕坐标
const clientToScreen = (x: number, y: number) => {
  const screenX = x + window.screenX
  const screenY = y + window.screenY + barHeight()
  return [screenX, screenY]
}

// 屏幕坐标 -- 视口坐标
const screenToClient = (x: number, y: number) => {
  const clientX = x - window.screenX
  const clientY = y - window.screenY - barHeight()
  return [clientX, clientY]
}

let dragStyle = ref(`left: ${x}px; top: ${y}px`)
const imgSrc = ref()
const init = () => {
  const {
    query: { type = 1 }
  } = route
  imgSrc.value = new URL(`../../assets/image/postMessage/${type}.jpg`, import.meta.url).href
}

onMounted(() => {
  init()
  sendMessage(x.value, y.value)
})
</script>

<style lang="scss" scoped>
.port-message {
  .drag-box {
    &:hover {
      cursor: move;
    }
  }
}
</style>
